import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:rembercount/controller/themeController.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

class CategoryController extends GetxController {
  final _categories = <Map<String, dynamic>>[].obs;
  final _categoriesKey = 'custom_categories';

  // 预定义所有可用的图标
  static const Map<String, IconData> availableIcons = {
    'restaurant': Icons.restaurant,
    'shopping_bag': Icons.shopping_bag,
    'directions_car': Icons.directions_car,
    'phone_android': Icons.phone_android,
    'home': Icons.home,
    'medical_services': Icons.medical_services,
    'school': Icons.school,
    'celebration': Icons.celebration,
    'fastfood': Icons.fastfood,
    'local_cafe': Icons.local_cafe,
    'local_bar': Icons.local_bar,
    'local_mall': Icons.local_mall,
  };

  List<Map<String, dynamic>> get categories => _categories;

  @override
  void onInit() {
    super.onInit();
    _loadCategories();
  }

  Future<void> _loadCategories() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final categoriesJson = prefs.getString(_categoriesKey);
      
      if (categoriesJson != null) {
        final List<dynamic> decoded = json.decode(categoriesJson);
        _categories.value = decoded.map((item) {
          final map = Map<String, dynamic>.from(item);
          final iconName = map['icon'] as String;
          final icon = availableIcons[iconName];
          if (icon == null) {
            print('Warning: Icon not found for name: $iconName');
            return {
              'icon': Icons.error,
              'name': map['name'],
              'color': Color(map['color'] as int),
            };
          }
          return {
            'icon': icon,
            'name': map['name'],
            'color': Color(map['color'] as int),
          };
        }).toList();
      } else {
        // 默认分类
        _categories.value = [
          {'icon': availableIcons['restaurant']!, 'name': '饮食', 'color': const Color(0xFF2D9596)},
          {'icon': availableIcons['shopping_bag']!, 'name': '购物', 'color': const Color(0xFF2D9596)},
          {'icon': availableIcons['directions_car']!, 'name': '交通', 'color': const Color(0xFF2D9596)},
          {'icon': availableIcons['phone_android']!, 'name': '通讯', 'color': const Color(0xFF2D9596)},
          {'icon': availableIcons['home']!, 'name': '住房', 'color': const Color(0xFF2D9596)},
          {'icon': availableIcons['medical_services']!, 'name': '医疗', 'color': const Color(0xFF2D9596)},
          {'icon': availableIcons['school']!, 'name': '教育', 'color': const Color(0xFF2D9596)},
          {'icon': availableIcons['celebration']!, 'name': '娱乐', 'color': const Color(0xFF2D9596)},
        ];
        await _saveCategories();
      }
    } catch (e) {
      print('Error loading categories: $e');
      // 如果加载失败，使用默认分类
      _categories.value = [
        {'icon': availableIcons['restaurant']!, 'name': '饮食', 'color': const Color(0xFF2D9596)},
        {'icon': availableIcons['shopping_bag']!, 'name': '购物', 'color': const Color(0xFF2D9596)},
        {'icon': availableIcons['directions_car']!, 'name': '交通', 'color': const Color(0xFF2D9596)},
        {'icon': availableIcons['phone_android']!, 'name': '通讯', 'color': const Color(0xFF2D9596)},
        {'icon': availableIcons['home']!, 'name': '住房', 'color': const Color(0xFF2D9596)},
        {'icon': availableIcons['medical_services']!, 'name': '医疗', 'color': const Color(0xFF2D9596)},
        {'icon': availableIcons['school']!, 'name': '教育', 'color': const Color(0xFF2D9596)},
        {'icon': availableIcons['celebration']!, 'name': '娱乐', 'color': const Color(0xFF2D9596)},
      ];
    }
  }

  Future<void> _saveCategories() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final categoriesToSave = _categories.map((category) {
        final iconData = category['icon'] as IconData;
        final iconName = availableIcons.entries
            .firstWhere(
              (entry) => entry.value.codePoint == iconData.codePoint,
              orElse: () => MapEntry('error', Icons.error),
            )
            .key;
        
        return {
          'icon': iconName,
          'name': category['name'],
          'color': (category['color'] as Color).value,
        };
      }).toList();
      
      await prefs.setString(_categoriesKey, json.encode(categoriesToSave));
    } catch (e) {
      print('Error saving categories: $e');
    }
  }

  Future<void> addCategory(String name, IconData icon) async {
    try {
      final themeController = Get.find<ThemeController>();
      _categories.add({
        'icon': icon,
        'name': name,
        'color': themeController.themeColor,
      });
      await _saveCategories();
    } catch (e) {
      print('Error adding category: $e');
    }
  }

  Future<void> removeCategory(int index) async {
    if (index >= 0 && index < _categories.length) {
      _categories.removeAt(index);
      await _saveCategories();
    }
  }

  Future<void> updateCategory(int index, String name, IconData icon) async {
    if (index >= 0 && index < _categories.length) {
      final themeController = Get.find<ThemeController>();
      _categories[index] = {
        'icon': icon,
        'name': name,
        'color': themeController.themeColor,
      };
      await _saveCategories();
    }
  }
} 